import Dep from "./dep.js"

function Observer(data, vm){
  this.vm = vm
  this.bindData(data)
}

Observer.prototype.bindData = function (data) {
  Object.keys(data).forEach(key=> {
    this.bindFunc(data, key, data[key])
  })
}

Observer.prototype.bindFunc = function (target, key, value) {
  if (typeof value === 'object') {
    this.bindData(value)
  }
  let dep = new Dep()
  const _this = this
  Object.defineProperty(target, key, {
    get () {
      // console.log('getter ==', value)
      Dep.target && dep.addWatcher(Dep.target)
      Dep.target = null
      return value
    },
    set(newVal) {
      if (newVal === value) return
      // console.log('setter ==', newVal)
      _this.vm.$option.beforeUpdate()
      value = newVal
      dep.notify()
      _this.vm.$option.updated()
    }
  })
}



export default Observer